/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.h2t.loveplace.utils;

import com.h2t.loveplace.models.Place;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.util.Vector;
import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordStore;

/**
 *
 * @author PHAN THAI
 */
public class PlaceStore {
    private final static String PLACE = "place2";
    
    public static void addToAlbum(Place place) {
        RecordStore rs = null;
        try {
            rs = RecordStore.openRecordStore(PLACE, true);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            DataOutputStream dos = new DataOutputStream(bos);

            dos.writeUTF(place.getTitle());   // Write name
            System.out.println("Img: " + place.getImg());
            dos.writeUTF(place.getImg());    // Write dir
            dos.writeUTF(place.getDescription());
            dos.writeDouble(place.getLat());
            dos.writeDouble(place.getLon());
            rs.addRecord(bos.toByteArray(), 0, bos.size());
            dos.close();
            bos.close();
        } catch (Exception e) {
        }
        closeRecordStrore(rs);
    }
    
    public static Vector getAllPlace() {
        Vector placelist = null;
        RecordStore rs = null;
        RecordEnumeration re = null;
        try {
            rs = RecordStore.openRecordStore(PLACE, false);
            re = rs.enumerateRecords(null, null, true);
            while (re.hasNextElement()) {
                int id = re.nextRecordId();
                byte[] data = rs.getRecord(id);
                ByteArrayInputStream bis = new ByteArrayInputStream(data);
                DataInputStream dis = new DataInputStream(bis);
                Place fi = new Place(id, dis.readUTF(), dis.readUTF(),
                        dis.readUTF(), dis.readDouble(), dis.readDouble());
                
                placelist.addElement(fi);
                dis.close();
                bis.close();
            }
        } catch (Exception e) {
        }
        closeRecordStrore(rs);
        return placelist;
    }

    private static void closeRecordStrore(RecordStore rs) {
        if (rs != null) {
            try {
                rs.closeRecordStore();
            } catch (Exception e) {
            }
        }
    }
}
